package com.appspot.javametronome.client.controller;

import com.appspot.javametronome.client.model.Bpm;
import com.appspot.javametronome.client.model.Tick;
import com.google.gwt.user.client.Timer;

public class TickController {

    public static final TickController instance = new TickController();

    private Tick hiTick; // TODO tick pattern
    private Tick loTick;
    private Timer timer;

    private TickController() {
        hiTick = new Tick("sounds/tick1-hi.mp3");
        loTick = new Tick("sounds/tick1-lo.mp3");
    }

    public void start(Bpm bpm) {
        timer = new Timer() {
            public void run() {
                loTick.play();
            }
        };

        int repeatTime = (int) BpmController.bpmToDelta(bpm.getDoubleValue());
        // Play once now
        playOnce();
        // Schedule the rest for playing
        timer.scheduleRepeating(repeatTime);
    }

    public void stop() {
        if (timer != null) {
            timer.cancel();
        }
    }

    public void playOnce() {
        loTick.play();
    }

}
